//
//  SpotCalculateTextView.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/2.
//

import UIKit

class SpotCalculateTextView: UIView,UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var textCount: UITextView!
    @IBOutlet weak var sureNumLabel: UILabel!
    @IBOutlet weak var bgView: UIView!

    var textMaxCount:Int = 0
    override func awakeFromNib() {
        super.awakeFromNib()
        self.textView.delegate = self
        self.bgView.layer.borderWidth = 0.5
        self.bgView.layer.borderColor = UIColor.init(hexString: "#B2B2B2").cgColor
    }
    func setTextMaxCount(textMaxCount:Int)  {
        self.textMaxCount = textMaxCount
        sureNumLabel.text = String.init(format: "%ld", textMaxCount)
    }
    
    func textViewDidChange(_ textView: UITextView) {
        self.textView.setContentOffset(CGPoint.init(x: 0, y: (self.textView.contentSize.height - self.textView.frame.size.height)/2), animated: true)
        var textStr:String = ""
        let selectedRange:NSRange = textView.selectedRange
        let range = textView.markedTextRange
        if range != nil {
            let position = textView.position(from: range!.start, offset: 0)
            if position == nil {
                if textView.text.count > textMaxCount {
                    self.textCount.text = String(textMaxCount)
                    textView.text = String(textView.text.prefix(textMaxCount))
                    textStr = textView.text
                    let textColor:NSMutableAttributedString = NSMutableAttributedString.init(string: textView.text)
                    textColor.addAttributes([.foregroundColor : UIColor.black], range: NSRange.init(location: 0, length: textView.text.count))
                    textView.attributedText = textColor
                } else {
                    let length = textView.text.count
                    self.textCount.text = String.init(format: "%lu", length)
                    self.textCount.textColor = UIColor.black
                    self.sureNumLabel.textColor = UIColor.black
                    let textColor:NSMutableAttributedString = NSMutableAttributedString.init(string: textView.text)
                    textColor.addAttributes([.foregroundColor : UIColor.black], range: NSRange.init(location: 0, length: textView.text.count))
                    textView.attributedText = textColor
                }
            }
        }
        //保留光标原来的位置.
        textView.selectedRange = selectedRange
    }
    

}
